<?php

namespace wx;

use traits\ResponsDataBuild;

class WxPay
{
    use ResponsDataBuild;

    public function config()
    {
        // 商户相关配置
        $merchantId = ''; // 商户号
        $merchantSerialNumber = ''; // 商户API证书序列号
        $filepath = "uploads/attach/2020/12/20201202/afba9ad6b68a66c144a36d9abbb8c52b.pem"; //私钥在本地的位置
        $file = file_get_contents($filepath);
        $mch_private_key = openssl_get_privatekey($file);

        $appid = ''; //小程序appid
        $out_trade_no = date('YmdHis', time()) . rand(1000, 9999);

        $data = [
            "appid" => $appid,
            "mchid" => $merchantId,
            "description" => '标题',
            'out_trade_no' => $out_trade_no,
            'notify_url' => '',  //回调地址
            "amount" => [
                "total" => 1,
                "currency" => "CNY"
            ],
            "payer" => [
                "openid" => "" //用户openid
            ]
        ];

        $timestamp = time();
        $nonce = date('YmdHis', time()) . rand(1000, 9999);
        $url = 'https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi';
        $url_parts = parse_url($url);
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));

        $data = json_encode($data);
        $message = 'POST' . "\n" .
            $canonical_url . "\n" .
            $timestamp . "\n" .
            $nonce . "\n" .
            $data . "\n";

        openssl_sign($message, $signature, $mch_private_key, "sha256WithRSAEncryption");
        $sign = base64_encode($signature);
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $merchantId, $nonce, $timestamp, $merchantSerialNumber, $sign);

        $header = "Authorization: " . $schema . " " . $token;

        $res = $this->http_post($url, $header, $data);
        $arr = json_decode($res, true);

        $time = time();
        $str = time() . round('1000', '9999');
        $prepay = 'prepay_id=' . $arr['prepay_id'];

        $message1 = $appid . "\n" .
            $time . "\n" .
            $str . "\n" .
            $prepay . "\n";

        openssl_sign($message1, $signature, $mch_private_key, "sha256WithRSAEncryption");
        $sign1 = base64_encode($signature);


        $data = array();
        $data['timeStamp'] = $time;
        $data['nonce'] = $str;
        $data['prepay_id'] = $arr['prepay_id'];
        $data['sign'] = $sign1;
        return $this->returnRight($data);
    }
}